#!/usr/bin/env bash
# ══════════════════════════════════════════════════════════════════════════════
# FurryOS: Sovereign Mansion Launcher (v2.1_v5)
# ══════════════════════════════════════════════════════════════════════════════
# This is the dedicated high-performance portal to the unpacked OS folder.
# ══════════════════════════════════════════════════════════════════════════════
set -e

PROJECT_ROOT="$(cd "$(dirname "$0")" && pwd)"
GENERATED="$PROJECT_ROOT/../_generated"
ISO_ROOT="$GENERATED/iso-root"
SQUASHFS_ROOT="$GENERATED/work/squashfs-root"

# 1. Verification
if [ ! -d "$SQUASHFS_ROOT" ]; then
    echo "❌ Error: Sovereign Mansion not found! Run ./build_furryos.sh first."
    exit 1
fi

echo "🦊 Preparing the portal to the Sovereign Mansion..."

# 2. Performance: Find the Hybrid MBR
MBR_BIN=$(find /usr/lib -name isohdpfx.bin 2>/dev/null | head -n 1 || echo "")

# 3. Grounding: Force the 'anthro' user in the boot config
# This ensures that even if you didn't run the full builder, the portal knows your name.
sudo find "$ISO_ROOT" -name "*.cfg" -type f -exec sed -i 's/boot=live/boot=live live-username=anthro/g' {} +

# 4. Rapid Sync (LZ4 is instant)
TEST_ISO="$GENERATED/mansion_portal.iso"
sudo rm -f "$ISO_ROOT/live/filesystem.squashfs"
echo "📦 GROUNDING: Unpacking latest changes into the virtual medium..."
sudo nice -n 19 mksquashfs "$SQUASHFS_ROOT" "$ISO_ROOT/live/filesystem.squashfs" \
    -comp lz4 -noappend -b 256K -info

# 🎨 BIOS Boot Splash Fix (ISOLINUX)
echo "🖼️ Branding the BIOS threshold..."
# Debian's BIOS menu looks for splash.png in the isolinux folder
if [ -f "$FURRYOS_SHARE/splash/splash.png" ]; then
    sudo mkdir -p "$ISO_ROOT/isolinux"
    sudo cp "$FURRYOS_SHARE/splash/splash.png" "$ISO_ROOT/isolinux/splash.png"

    # We also need to tell the config to actually display it
    sudo sed -i 's/menu background.*/menu background splash.png/g' "$ISO_ROOT/isolinux/stdmenu.cfg" 2>/dev/null || true
    echo "  ✓ BIOS splash applied."
fi

# 5. Build the "Portal" ISO (Fixes Checksum and Medium Detection)
echo "💿 STABILIZING: Rebuilding Boot Info Tables..."
sudo xorriso -as mkisofs \
    -iso-level 3 -full-iso9660-filenames -volid "FurryOS" \
    -eltorito-boot isolinux/isolinux.bin -eltorito-catalog isolinux/boot.cat \
    -no-emul-boot -boot-load-size 4 -boot-info-table \
    ${MBR_BIN:+-isohybrid-mbr "$MBR_BIN"} \
    -output "$TEST_ISO" "$ISO_ROOT" 2>/dev/null

# 6. Launch with High Specs (The "Mansion" Experience)
echo "🚀 PORTAL OPEN: Master Tempter is arriving..."
# -m 3G: Gives the VM 3GB of RAM for a smooth experience
# -smp 4: Gives it 4 CPU cores
# -cpu host: Uses your actual processor power
sudo qemu-system-x86_64 -cdrom "$TEST_ISO" -m 2G -smp 4 -enable-kvm -vga virtio -display gtk,gl=on,zoom-to-fit=on -usb -device usb-tablet

# 7. Cleanup
sudo rm -f "$TEST_ISO"
